import { UserConfig, ConfigEnv } from 'vite';
import { createVitePlugins } from './build/vite/plugins';
import { resolve } from 'path';
import { VITE_PORT } from './build/constant';

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

// https://vitejs.dev/config/
export default ({ command }: ConfigEnv): UserConfig => {
  const isBuild = command === 'build';
  let base: string;
  if (command === 'build') {
    base = '/';
  } else {
    base = '/';
  }
  return {
    base,
    publicDir: "public", //静态资源服务的文件夹
    resolve: {
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        },
        // 别名 /@/xxxx => src/xxxx
        {
          find: '/@',
          replacement: pathResolve('src') + '/',
        },
        // 添加更多别名以确保路径解析正确
        {
          find: '@',
          replacement: pathResolve('src') + '/',
        },
      ],
    },
    // plugins
    plugins: createVitePlugins(isBuild),

    // css
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },

    // 构建优化
    build: {
      target: 'es2015',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'vue-router', 'pinia'],
            antd: ['ant-design-vue'],
            icons: ['@ant-design/icons-vue'],
          },
        },
      },
      chunkSizeWarningLimit: 1000,
    },

    // 开发服务器优化
    server: {
      hmr: { 
        overlay: false,
        port: 24678, // 指定HMR端口
      },
      port: VITE_PORT,
      open: false,
      cors: true,
      host: '0.0.0.0',
      https: false,
      // 添加代理配置
      proxy: {
        '/api': {
          target: 'http://localhost:8081',
          changeOrigin: true,
          secure: false,
        },
      },
    },

    // 依赖预构建优化
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'pinia',
        'ant-design-vue',
        '@ant-design/icons-vue',
        'axios',
      ],
      exclude: [],
    },

    // 预构建选项
    esbuild: {
      pure: ['console.log', 'debugger'],
    },
  };
};
